package com.chat.ui.recyclerview;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chat.MyApplication;
import com.chat.R;
import com.chat.entity.DataPackage;
import com.chat.entity.Room;
import com.chat.entity.ServerAction;
import com.chat.entity.event.ChannelEvent;
import com.chat.net.SocketClient;
import com.chat.net.socket.Channel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Address book 群聊页面
 */
public class RecyclerViewFragment extends Fragment {

    private RecyclerViewViewModel mViewModel;
    RecyclerView recyclerView;
    private MyRecycleViewAdapter adapter;
    private List<HashMap<String,Object>> mData=new ArrayList<HashMap<String,Object>>();

    public static RecyclerViewFragment newInstance() {
        return new RecyclerViewFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recyclerview, container, false);
        recyclerView=view.findViewById(R.id.recycler_view);
        getData();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));//垂直线性布局
        adapter=new MyRecycleViewAdapter();
        recyclerView.setAdapter(adapter);
        return view;
    }


    private void getData() {
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == 200){
                    Toast.makeText(getActivity(), "更新数据"+mData.size(), Toast.LENGTH_SHORT).show();
                    adapter.notifyDataSetChanged();
                }
            }
        };
        //发送请求
        DataPackage dataPackage = DataPackage.request(ServerAction.GET_ROOMS_BY_USER);
//        ChatObjectServer.getServer().addObject(dataPackage);
        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {//添加处理事件
            public void onChannelEvent(Channel ctx, DataPackage source) {
                mData.clear();
                List<Room> rooms = (List<Room>) source.getDate();
                for(Room room:rooms){
                    if(room!=null) {
                        HashMap<String, Object> item = new HashMap<>();
                        item.put("name", room.getName());
                        item.put("lastMessage", String.valueOf(room.getRoomId()));
                        item.put("time", "2022-08-10");
                        item.put("id", room.getRoomId());
                        item.put("picture", R.drawable.dog);
                        mData.add(item);
                    }
                }
                Message message = Message.obtain();
                message.what = source.getCode();
                handler.sendMessage(message);
            }
        },dataPackage);

//        //初始化数据
//        for(int i = 0 ; i < 10 ; i++){
//            HashMap<String,Object> item = new HashMap<>();
//            item.put("name","群聊"+i);
//            item.put("lastMessage","最后的信息"+i);
//            item.put("time","2022-11-17");
//            item.put("picture",R.drawable.dog);
//            mData.add(item);
//        }

    }
    //自定义Adapter
    class  MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.ViewHolder>
    {


        public  class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView picture;
            public TextView time;
            public TextView lastMessagae;
            public TextView name;

            public ViewHolder(View convertView) {
                super(convertView);
                picture = (ImageView)convertView.findViewById(R.id.item_chat_head);
                time = (TextView)convertView.findViewById(R.id.item_chat_time);
                lastMessagae = (TextView)convertView.findViewById(R.id.item_chat_lastmessage);
                name = (TextView)convertView.findViewById(R.id.item_chat_name);
            }
        }
        @NonNull
        @Override
        public MyRecycleViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v= LayoutInflater.from(getActivity()).inflate(R.layout.item,parent, false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(@NonNull MyRecycleViewAdapter.ViewHolder holder, final int position) {
            //picture
            Glide.with(getActivity()).load(new MyApplication().imagebaseurl+mData.get(position).get("picture").toString()).placeholder(R.drawable.dog).into(holder.picture);
            holder.name.setText((String)mData.get(position).get("name"));
            holder.time.setText((String)mData.get(position).get("time"));
            holder.lastMessagae.setText((String)mData.get(position).get("lastMessage"));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    NavController navController= Navigation.findNavController(getActivity(),R.id.nav_host_fragment);
                    Bundle bundle=new Bundle();
                    bundle.putInt("id",(int)mData.get(position).get("id"));
                    navController.navigate(R.id.detailFragment,bundle);

                }
            });
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }
}
